package com.auxgroup.smarthome.controller;

import com.auxgroup.smarthome.filter.PermissionSecurityUserService;
import com.auxgroup.smarthome.filter.annotation.PermissionFilter;
import com.auxgroup.smarthome.jwt.JwtConstant;
import com.auxgroup.smarthome.jwt.JwtUtils;
import com.auxgroup.smarthome.syscode.Syscode;
import com.auxgroup.smarthome.vo.AccessTokenVo;
import com.auxgroup.smarthome.web.ApiResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by kevinchen on 2017/2/25.
 */
@Api( tags = "系统登录")
@RestController
public class RefreshTokenController {
    @Autowired
    private PermissionSecurityUserService permissionSecurityUserService;

    @ApiOperation(value = "刷新accessToken")
    @RequestMapping(value = "/refreshtoken",method = RequestMethod.POST)
    @PermissionFilter(filter = true)
    public ApiResponse refreshToken(@RequestHeader("token") String token) throws Exception {
        String uid = permissionSecurityUserService.getSubjectFromAccessToken();
        if(StringUtils.isEmpty(uid)) {
            return ApiResponse.prompt(Syscode.JWT_REFRESHTOKEN_INVALID);
        }
        String refreshToken = JwtUtils.createJWT(JwtConstant.JWT_SECRET,System.currentTimeMillis(),JwtConstant.JWT_ID, uid, JwtConstant.JWT_TTL);
        AccessTokenVo accessTokenVo = new AccessTokenVo(refreshToken, "bearer", JwtConstant.JWT_REFRESH_INTERVAL);
        return ApiResponse.ok(accessTokenVo);
    }

}
